package com.lwq.fast.log.trace.interceptor;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.lwq.fast.log.fastlogcore.constant.Constants;
import com.lwq.fast.log.fastlogcore.trace.TraceThreadLocal;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * @author 刘文强
 *
 * RestTemplate 拦截器
 */
@Component
public class RestTemplateHeaderInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        String traceId = TraceThreadLocal.get();
        if (StrUtil.isBlank(traceId)){
            traceId = IdUtil.simpleUUID();
        }
        httpRequest.getHeaders().add(Constants.TRACE_ID, traceId);
        return clientHttpRequestExecution.execute(httpRequest, bytes);
    }
}
